<template>
  <div class="channel-edit">
    <van-cell :border="false">
      <div slot="title" class="title-text">我的频道</div>
      <van-button
        class="edit-btn"
        size="mini"
        round
        type="danger"
        @click="isEdit = !isEdit"
        plai
        >{{ isEdit ? '完成' : '编辑' }}</van-button
      >
    </van-cell>
    <van-grid class="my-grid" :gutter="10">
      <van-grid-item
        class="grid-item"
        v-for="(channel, index) in myChannels"
        :key="index"
        @click="onMyChannelClick(channel, index)"
      >
        <van-icon
          v-show="isEdit && fiexdChannels.includes(channel.id) === false"
          slot="icon"
          name="clear"
        ></van-icon>
        <span class="text" :class="{ actives: index === active }" slot="text">{{
          channel.name
        }}</span>
      </van-grid-item>
    </van-grid>
    <van-cell :border="false">
      <div slot="title" class="title-text">频道推荐</div>
    </van-cell>
    <van-grid class="recomment-grid" :gutter="10">
      <van-grid-item
        icon="plus"
        class="grid-item"
        v-for="(channel, index) in recommendChannele"
        :key="index"
        :text="channel.name"
        @click="onAddChannel(channel)"
      />
    </van-grid>
  </div>
</template>

<script>
import {
  getAllChannels,
  addUserChannel,
  deleteUserChannel
} from '@/api/channel.js'
import { setItem } from '@/utils/storage.js'
import { mapState } from 'vuex'
export default {
  name: 'ChannelEdit',
  data() {
    return {
      allChannels: [], // 所有频道
      isEdit: false, // 控制编辑状态
      fiexdChannels: [0] // 不需要编辑、删除的频道
    }
  },
  props: {
    myChannels: {
      type: Array,
      required: true
    },
    active: {
      type: Number,
      required: true
    }
  },
  created() {
    this.loadAllChannels()
  },
  methods: {
    // 获取所有频道列表数据
    async loadAllChannels() {
      try {
        const { data } = await getAllChannels()
        this.allChannels = data.data.channels
        // console.log(this.allChannels)
      } catch (err) {
        this.$toast('获取所有频道数据失败')
      }
    },
    // 添加频道
    async onAddChannel(channel) {
      this.myChannels.push(channel)
      // 持久化处理 通过判断是否存在token来确定是否登录
      if (this.user) {
        // 已登录,把数据放到服务器
        try {
          await addUserChannel({
            id: channel.id, // 频道 ID
            seq: this.myChannels.length // 序号
          })
        } catch (err) {
          this.$toast('保存失败,请稍后再试')
        }
      } else {
        // 未登录，把数据存储到本地
        setItem('TOUTIAO_CHANNELS', this.myChannels)
      }
    },
    // 判断当前是否为编辑状态，如果是编辑状态就做删除操作，如果不是就切换频道
    onMyChannelClick(channel, index) {
      if (this.isEdit) {
        // 删除操作
        // 如果是固定频道，则不能删除
        if (this.fiexdChannels.includes(channel.id)) {
          return
        }
        this.myChannels.splice(index, 1)
        // 如果删除的频道项是激活频道项之前的频道，则更新激活频道项
        if (index <= this.active) {
          // 让激活频道索引 - 1
          this.$emit('update-active', this.active - 1, true)
        }
        // 数据持久化
        this.deleteChannel(channel)
      } else {
        // 子传父，切换频道
        this.$emit('update-active', index, false)
      }
    },
    // 删除操作的持久化
    async deleteChannel(channel) {
      try {
        if (this.user) {
          // 已登录,则将数据更新到服务器上
          await deleteUserChannel(channel.id)
        } else {
          // 未登录,将数据更新到本地
          setItem('TOUTIAO_CHANNELS', this.myChannels)
        }
      } catch (err) {
        this.$toast('操作失败,请稍后重试')
      }
    }
  },
  computed: {
    // recommendChannele () {
    //   const channels = []
    //   this.allChannels.forEach(channel => {
    //     // 使用 find 遍历数组，找到满足条件的元素项
    //     const ret = this.myChannels.find(userChannels => {
    //       return userChannels.id === channel.id
    //     })
    //     // 如果我的频道中不包括该频道项，则收集到推荐频道中
    //     if (!ret) {
    //       channels.push(channel)
    //     }
    //   })
    //   return channels
    // }
    recommendChannele() {
      // 数组的 filter 方法：遍历数组，把符合条件的元素存储到新数组中
      return this.allChannels.filter((channel) => {
        // 数组的 find 方法：遍历数组，把符合条件的第一个元素返回
        return !this.myChannels.find((myChannel) => {
          return myChannel.id === channel.id
        })
      })
    },
    ...mapState(['user'])
  }
}
</script>

<style scoped lang="less">
.channel-edit {
  padding: 85px 0px;
  .title-text {
    font-size: 32px;
    color: #333;
  }
  .edit-btn {
    width: 104px;
    height: 48px;
    background-color: #fff;
    font-size: 26px;
    color: #f85959;
    border: 1px solid #f85959;
  }
  /deep/ .grid-item {
    width: 160px;
    height: 86px;
    .van-grid-item__content {
      white-space: nowrap;
      background-color: #f4f5f6;
      .van-grid-item__text,
      .text {
        font-size: 22px;
        color: #222;
        margin-top: 4px !important;
      }
      .actives {
        color: red;
      }
      .van-grid-item__icon-wrapper {
        position: unset;
      }
    }
  }
  /deep/ .my-grid {
    .grid-item {
      .van-icon-clear {
        position: absolute;
        right: -10px;
        top: -10px;
        font-size: 30px;
        color: #cacaca;
        z-index: 2;
      }
    }
  }
  /deep/ .recomment-grid {
    .grid-item {
      width: 160px;
      height: 86px;
      .van-grid-item__content {
        flex-direction: row;
        .van-icon-plus {
          font-size: 22px;
          line-height: 22px;
          margin-right: 6px;
        }
      }
    }
  }
}
</style>
